package com.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.dao.FileDao;
import com.pojo.Archive;
import com.service.ArchiveService;
import com.service.FileService;
import com.util.MySqlSessionFactory;

@Controller
public class FileController {
	ArchiveService achs = new ArchiveService();
	FileService fs = new FileService();

	/**
	 * 上传图片
	 */
	@RequestMapping(value = "/{id}/upload.action", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@PathVariable String id,
			@RequestParam("file") MultipartFile file, HttpServletRequest req) {
		if (file.isEmpty()) {
			System.out.println("未选择文件");
			return "ERROR_NO_FILE";
		}
		try {
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			String fileExtension = fileName
					.substring(fileName.lastIndexOf(".") + 1);
			String newFileName = String.valueOf(System.currentTimeMillis())
					+ "." + fileExtension;
			List<Archive> archive = achs.query_one(id);
			// System.out.println(archive.get(0).getArchive_id());
			String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
					.getServletContext().getRealPath("/"), "upload", archive
					.get(0).getArchive_id(), newFileName);
			File existsFile = new File(filePath);
			//System.out.println(existsFile);
			if (!existsFile.getParentFile().exists()) {
				if (!existsFile.getParentFile().mkdirs()) {
					System.out.println("创建目录失败");
					return "ERROR_ON_MKDIR";
				}
			}
			if (existsFile.exists()) {
				if (existsFile.delete()) {
					// System.out.println("删除原始文件：" + filePath);
				} else {
					System.out.println("删除文件失败：" + filePath);
				}
			}
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(new File(filePath)));
			stream.write(bytes);
			stream.close();
			fs.insertPages(archive.get(0).getId(), newFileName);
			return "OK";
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
	}

	/**
	 * 在页面显示图片
	 */
	@RequestMapping(value = "queryFile.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> queryFile(
			@RequestParam(value = "id", defaultValue = "") String id) {
		SqlSession session = MySqlSessionFactory.getSqlSession();
		FileDao dao = session.getMapper(FileDao.class);
		List<Map<String, Object>> file = dao.queryFile(id);
		return file;
	}

	/**
	 * 把一个图片通过id传到另一个页面做删除
	 */
	@RequestMapping(value = "querydel.action", method = RequestMethod.GET)
	@ResponseBody
	public List<Map<String, Object>> querydel(
			@RequestParam(value = "id", defaultValue = "") String id) {
		SqlSession session = MySqlSessionFactory.getSqlSession();
		FileDao dao = session.getMapper(FileDao.class);
		List<Map<String, Object>> file1 = dao.querydel(id);
		// System.out.println(id);
		// System.out.println(file1);
		return file1;
	}

	/**
	 * 删除数据库和服务器中的记录图片一条
	 * 
	 */
	@RequestMapping(value = "delfile.action", method = RequestMethod.POST)
	@ResponseBody
	public String delfile(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletRequest req) {
		SqlSession session = MySqlSessionFactory.getSqlSession();
		FileDao dao = session.getMapper(FileDao.class);
		Map<String, Object> map = dao.queryf(id);
		String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
				.getServletContext().getRealPath("/"), "upload", map.get("ac"),
				map.get("fn"));
		File existsFile = new File(filePath);
		existsFile.delete();
		fs.delfile(id);
		session.commit();
		return "OK";
	}

}
